package gw.com.android.ui.chart;

import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import com.gwtsz.android.rxbus.RxBus;
import com.gwtsz.chart.components.XAxis;
import com.gwtsz.chart.components.YAxis;
import com.gwtsz.chart.highlight.Highlight;
import com.gwtsz.chart.listener.onChartStateListenner;
import com.gwtsz.chart.output.bean.KLineBean;
import com.gwtsz.chart.output.customer.MyCombinedChart;
import com.gwtsz.chart.output.utils.ChartConfig;
import com.gwtsz.chart.output.utils.ChartThemeUtil;
import com.gwtsz.chart.output.utils.GTTFormularContent;
import com.gwtsz.chart.output.utils.GTTFormularParam;
import com.gwtsz.chart.output.utils.GTTIndexDataRequest;
import com.gwtsz.chart.output.utils.GTTIndicatorsModel;
import com.gwtsz.chart.output.utils.GTTKDataManager;
import com.gwtsz.chart.output.utils.GTTKDataModel;
import com.gwtsz.chart.output.utils.GTTLineModel;
import com.gwtsz.chart.output.utils.GTTNotifyModel;
import com.gwtsz.chart.output.utils.Periodicity;
import com.gwtsz.gts2.hx.R;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import gw.com.android.app.ActivityManager;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.model.DataManager;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.ui.chart.manager.ChartKViewImp;
import gw.com.android.ui.chart.manager.ChartKViewInterface;
import gw.com.android.ui.chart.manager.InterceptView;
import gw.com.android.ui.chart.views.ChartIndicatorPopWindow;
import gw.com.android.ui.chart.views.ChartPriceBar;
import gw.com.android.ui.dialog.BaseDialog;
import gw.com.android.ui.dialog.DialogDismissedListener;
import gw.com.android.ui.quote2.widget.OnQuoteChartProgressStatusChangeListener;
import gw.com.android.utils.ColorThemeUtil;
import gw.com.android.utils.ServerConnnectUtil;
import gw.com.android.utils.ThreadPool;
import gw.com.jni.library.terminal.GTSConst;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import www.com.library.app.Logger;
import www.com.library.app.PushMsgTabFragment;
import www.com.library.model.DataItemDetail;
import www.com.library.util.DoubleConverter;
import www.com.library.util.NetworkMonitor;
import www.com.library.util.ProductPrecision;
import www.com.library.view.RecyclerClickListener;
import www.com.library.view.TintTextView;
import www.com.library.view.UISpannableStringBuilder;

/**
 * Created by reeta.zou on 2016/10/13.
 * k线界面
 */
public class ChartKFragment extends PushMsgTabFragment {

    @BindView(R.id.main_rl)
    InterceptView main_rl;
    @BindView(R.id.kchart_view)
    MyCombinedChart mKChartView;
    @BindView(R.id.vice_chart_view)
    MyCombinedChart mViceChartView;
    ChartKViewInterface ChartKViewInterfaceimp;
    @BindView(R.id.view_divider)
    View mViewDivider;
    @BindView(R.id.main_layout)
    LinearLayout mMainLayout;
    @BindView(R.id.second_layout)
    LinearLayout mSecondLayout;
    @BindView(R.id.main_btn)
    TintTextView mMainBtn;
    @BindView(R.id.second_btn)
    TintTextView mSecondBtn;
    @BindView(R.id.main_title)
    TextView mMainTitleView;
    @BindView(R.id.second_title)
    TextView mSecondTitleView;
    @BindView(R.id.arrow_view)
    ImageView mArrowView;
    @BindView(R.id.start_tv)
    TextView start_tv;
    @BindView(R.id.end_tv)
    TextView end_tv;
    @BindView(R.id.main_set_btn)
    ImageView mMainSet;
    @BindView(R.id.second_set_btn)
    ImageView mSecondSet;
    @BindView(R.id.main_btn_layout)
    RelativeLayout mMainTarget;
    @BindView(R.id.second_btn_layout)
    RelativeLayout mSecondTarget;

    /**
     * 顶部title字符串处理对象
     */
    private UISpannableStringBuilder m_spannableTitle;
    public ChartPriceBar mPriceBar;
    private ChartIndicatorPopWindow mIndicatorPop;
    private Periodicity mPeriodicity;
    private ProductPrecision mPrecision;
    private int mUiCode;//产品code
    private int zoneType;
    private DataItemDetail mTickModel;
    public boolean isLoading = false;
    public int mCurSecondIndictor = 0;
    /*private GTTFormularContent mSuperFormularContent;
    private GTTFormularContent mSecondFormularContent;*/
    private int decimalNum = 0;
    private static String TAG = ChartKFragment.class.getSimpleName();
    private static String METHOD = "class=" + TAG + " method=";
    private boolean isHaveData = false;//数据是否正常
    private long start = 0;
    private long end = 0;
    private long timeInterval = 100;
    private int mCurrOffset = -1;
    private OnQuoteChartProgressStatusChangeListener onStatusChangeListener;
    private OnPriceBarListener priceBarListener;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_chart_k;
    }

    @Override
    public void setArguments(Bundle args) {
        super.setArguments(args);
        mUiCode = getArguments().getInt("uiCode", 0);
        zoneType = getArguments().getInt("zoneType", GTSConst.ZONE_TYPE_FX);
    }

    @Override
    protected void initLayoutView() {
        ButterKnife.bind(this, mRootView);
        isLording();
        setRenderer();
        ChartKViewInterfaceimp = new ChartKViewImp(mKChartView, mViceChartView, getActivity());
        mViceChartView.setOnChartStateListenner(new onChartStateListenner() {
            @Override
            public void onShowCursor(boolean enabled) {

            }

            @Override
            public void onHideCursor() {

            }

            @Override
            public void onUpdateIndictor(int curOffset) {

            }

            @Override
            public void onDrawCursor(double closePrice, GTTKDataModel dataModel) {

            }

            @Override
            public void onNextIndictor() {
                Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName());
                mCurSecondIndictor = (mCurSecondIndictor + 1) % ChartTypeData.instance().getChartInfIndicator().length;
                ChartConfig.instance().setSecondKType(ChartTypeData.instance().getChartInfIndicator(mCurSecondIndictor));
                ChartConfig.instance().saveSecondKType();
                AppTerminal.instance().asyncCalcIndicator(mUiCode);
            }

            @Override
            public void onShowRightArrow(boolean hasShow) {

            }

            @Override
            public void onRespon(int ViewIndexRightTime, int ViewNumber) {

            }

            @Override
            public void updata(int fristTime) {

            }

            @Override
            public void onResultData(String start, String end) {

            }

            @Override
            public void onHighlightValue(Highlight[] Highlight) {
                mKChartView.highlightValues(Highlight);
            }

            @Override
            public void onTouch(MotionEvent ev) {

            }
        });
        mKChartView.setOnChartStateListenner(new onChartStateListenner() {
            @Override
            public void updata(int fristTime) {
                Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName() + ",fristTime=" + fristTime);
                if (!isLoading && NetworkMonitor.hasNetWork()) {
                    GTTKDataModel model = GTTKDataManager.instance().getKLineModel(0);
                    if (null != model && !ReqDataUtils.instance().isReqLastest) {
                        isLording();
                        isLoading = true;
                        onProgressVisible(true);
                        ReqDataUtils.instance().reqKLineData(mUiCode, zoneType, mPeriodicity.nativeKLineType(), model.priceTime);
                    }
                }
            }

            @Override
            public void onShowCursor(boolean enabled) {
                Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName() + ",enabled=" + enabled);
                if (null != mPriceBar) {
                    mPriceBar.isCursor = enabled;
                }
                if (priceBarListener != null) {
                    priceBarListener.onShowCursor(enabled);
                }
            }

            @Override
            public void onHideCursor() {
                Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName());
                if (null != mPriceBar) {
                    mPriceBar.isCursor = false;
                    DataItemDetail model = DataManager.instance().getTickModel(mUiCode);
                    if (null != model) {
                        mPriceBar.setTickData(model);
                    }
                }
                if (priceBarListener != null) {
                    priceBarListener.onHideCursor(mUiCode);
                }
            }

            @Override
            public void onUpdateIndictor(int curOffset) {
                Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName() + ",curOffset=" + curOffset);
                updateIndicatorTitle(curOffset);
            }

            @Override
            public void onDrawCursor(double closePrice, GTTKDataModel dataModel) {
                Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName() + ",closePrice=" + closePrice + ",dataModel=" + dataModel);
                if (null != mPriceBar) {
                    mPriceBar.setCursorData(closePrice, dataModel, mPrecision);
                }
                if (priceBarListener != null) {
                    priceBarListener.onDrawCursor(closePrice, dataModel, mPrecision);
                }
            }

            @Override
            public void onNextIndictor() {
            }

            @Override
            public void onShowRightArrow(boolean hasShow) {
                Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName() + ",hasShow=" + hasShow);
                if (hasShow) {
                    mArrowView.setVisibility(View.VISIBLE);
                } else {
                    mArrowView.setVisibility(View.GONE);
                }
            }

            @Override
            public void onRespon(int ViewIndexRightTime, int ViewNumber) {

            }

            @Override
            public void onResultData(String start, String end) {
                if (start.length() > 10) {
                    start_tv.setText(start.substring(5));
                    end_tv.setText(end.substring(5));
                } else {
                    start_tv.setText(start);
                    end_tv.setText(end);
                }
            }

            @Override
            public void onHighlightValue(Highlight[] Highlight) {
                if (null != mViceChartView && ChartConfig.instance().isSecondChartOn()) {
                    mViceChartView.highlightValues(Highlight);
                }
            }

            @Override
            public void onTouch(MotionEvent ev) {

            }
        });
        mTickModel = DataManager.instance().getTickModel(mUiCode);
        onShowSecond();
    }

    @Override
    protected void initViewData() {
        mPeriodicity = ChartConfig.instance().getChartPeriodicity();
        m_spannableTitle = new UISpannableStringBuilder();
        if (null != mTickModel) {
            mPrecision = new ProductPrecision(0, mTickModel.getInt(GTSConst.JSON_KEY_DIGITS));
            /* new chart **/
            ChartKViewInterfaceimp.setProductPrecision(mPrecision);
            decimalNum = mPrecision.mNumOfDecimalsPoint;
            //ChartKViewInterfaceimp.refreshData(mUiCode,zoneType,mPeriodicity.nativeKLineType());
        }
        mCurSecondIndictor = ChartTypeData.instance().getChartInfIndicator(ChartConfig.instance().getSecondKType());
        mMainBtn.setText(ChartConfig.instance().getMainKType());
        mSecondBtn.setText(ChartConfig.instance().getSecondKType());
        //mSuperFormularContent = new GTTFormularContent();
        //mSecondFormularContent = new GTTFormularContent();
        //setIndictors();
        if (GTTKDataManager.instance().hasKLineData()) {
            onRefreshData(mUiCode, 0, GTTKDataManager.instance().mSuperFormularContent, GTTKDataManager.instance().mSecondFormularContent);
        } else {
            reqData();
        }

        if (onStatusChangeListener != null) {
            onNightMode(onStatusChangeListener.isNight());
        }
    }

    public void setRenderer() {
        Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName());
        if (null != mKChartView && null != ChartKViewInterfaceimp) {
            ChartKViewInterfaceimp.setPaintStype();
            //mKChartView.invalidate();
        }
    }

    /**
     * 设置报价区域对象
     */
    public void setPriceBar(ChartPriceBar priceBar) {
        Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName() + ",priceBar=" + priceBar);
        mPriceBar = priceBar;
    }

    /**
     * 重置面板各按钮布局
     */
    private void resetParams() {
        Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName());

        //设置放大缩小按钮的LayoutParams
        LayoutParams mBtnParam = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        mBtnParam.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        mBtnParam.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        if (isAdded()) {
            mBtnParam.rightMargin = (int) (getResources().getDimension(R.dimen.height_e));
        }
        //mBtnParam.bottomMargin= (int) getResources().getDimension(R.dimen.space_b) ;
        mBtnParam.bottomMargin = (int) mKChartView.getViewPortHandler().offsetBottom() + (int) ChartConfig.getDensity() * 10;
        /*if(ChartConfig.instance().isSecondChartOn()){
            mBtnParam.bottomMargin += (int) ChartConfig.getDensity() * 10;
        }*/
        mArrowView.setLayoutParams(mBtnParam);
        mArrowView.setVisibility(View.GONE);
    }

    /**
     * 是否显示副图指标
     */
    private void onShowSecond() {
        Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName());
        if (ChartConfig.instance().isSecondChartOn()) {
            mViewDivider.setVisibility(View.VISIBLE);
            mSecondLayout.setVisibility(View.VISIBLE);
        } else {
            mSecondLayout.setVisibility(View.GONE);
            mViewDivider.setVisibility(View.GONE);
        }
        ChartKViewInterfaceimp.setVisibility(ChartConfig.instance().isSecondChartOn());
        //resetParams();
    }

    /**
     * 清理界面指标参数
     */
    public void resetIndictor() {
        Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName());
        GTTKDataManager.instance().mSuperFormularContent = new GTTFormularContent();
        GTTKDataManager.instance().mSecondFormularContent = new GTTFormularContent();
        /*mSuperFormularContent = new GTTFormularContent();
        mSecondFormularContent = new GTTFormularContent();*/
        //setIndictors();
    }

    /**
     * 设置指标参数值
     */
    private void setIndictors(GTTFormularContent main, GTTFormularContent second) {
        Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName());
        if (GTTKDataManager.instance().mSuperFormularContent.mName == null || !GTTKDataManager.instance().mSuperFormularContent.mName.equals(ChartConfig.instance().getMainKType())) {
            GTTKDataManager.instance().mSuperFormularContent.mParamList.clear();
            GTTKDataManager.instance().mSuperFormularContent = main;
        }
        if (GTTKDataManager.instance().mSecondFormularContent.mName == null || !GTTKDataManager.instance().mSecondFormularContent.mName.equals(ChartConfig.instance().getSecondKType())) {
            GTTKDataManager.instance().mSecondFormularContent.mParamList.clear();
            GTTKDataManager.instance().mSecondFormularContent = second;
        }
    /*mSuperFormularContent.print();
    mSecondFormularContent.print();*/
        mMainBtn.setText(ChartConfig.instance().getMainKType());
        mSecondBtn.setText(ChartConfig.instance().getSecondKType());
    }

    /**
     * 切换指标
     */
    public void changedIndictors(GTTFormularContent main, GTTFormularContent sercond) {
        Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName());
        onShowSecond();
        //setIndictors();
        setIndictors(main, sercond);
        updateIndicatorTitle(GTTKDataManager.instance().mCacheList.size() + 1);

        if (!isLoading && null != mViceChartView && null != mKChartView && null != GTTKDataManager.instance().mSuperIndicators && null != GTTKDataManager.instance().mSecondIndicators) {
            isLoading = true;
            ChartKViewInterfaceimp.setMainIndicator(GTTKDataManager.instance().mSuperIndicators);
            ChartKViewInterfaceimp.setViceIndicator(GTTKDataManager.instance().mSecondIndicators);
            ChartKViewInterfaceimp.refreshIndicator();
            //mKChartView.notifyDataSetChanged();
            mKChartView.invalidate();
            //mViceChartView.notifyDataSetChanged();
            mViceChartView.invalidate();
            isLoading = false;
        }
    }

    @Override
    public void registerRxBus() {
        Disposable kdataListRegister = RxBus.getInstance().register(GTSConst.REPLY_KLINEDATA_LIST + "", Bundle.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bundle>() {

                    @Override
                    public void accept(@NonNull Bundle bundle) throws Exception {
                        if (null == bundle) {
                            return;
                        }
                        GTTNotifyModel obj = (GTTNotifyModel) bundle.getSerializable("GTTNotifyModel");
                        GTTFormularContent mSuperFormularContent = (GTTFormularContent) bundle.getSerializable("SuperFormular");
                        GTTFormularContent mSecondFormularContent = (GTTFormularContent) bundle.getSerializable("SecondFormular");
                        ArrayList<GTTKDataModel> mKLineList = (ArrayList<GTTKDataModel>) bundle.getSerializable("mKLineList");
                        GTTIndexDataRequest mGttIndexDataRequest = (GTTIndexDataRequest) bundle.getSerializable("mGttIndexDataRequest");
                        if (null != mGttIndexDataRequest) {
                            if (obj.uiAppend == 0) {
                                GTTKDataManager.instance().clearKData();
                            }
                            GTTKDataManager.instance().clearIndictor();
                            GTTKDataManager.instance().addAllKLineData(mKLineList);
                            Logger.i("onServerResponse AllKLineData.size = " + GTTKDataManager.instance().kLineNumbers);
                            ReqDataUtils.instance().copyIndictorData(mGttIndexDataRequest);
                            Logger.i("onServerResponse mSuperIndicators = "
                                    + GTTKDataManager.instance().mSuperIndicators.mName
                                    + ", "
                                    + GTTKDataManager.instance().mSuperIndicators.mLineList.size());
                        }
                        if (bundle.getInt("iValue") != 0) {
                            if (obj.nShNum == 0 && obj.uiAppend == 0) {
                                noDate(bundle.getInt("iValue"));
                            } else if (bundle.getInt("iValue") == 1059) {
                                // 请求K线数据超时
                                noDate(bundle.getInt("iValue"));
                            } else {
                                onFailDeal(bundle.getInt("iValue"));
                            }
                        } else if (null != obj && obj.uiCodeID == mUiCode
                                && obj.uiInterval == ChartConfig.instance()
                                .getChartPeriodicity()
                                .nativeKLineType()) {
                            onRefreshData(obj.uiCodeID, GTTKDataManager.instance().kLineNumbers,
                                    mSuperFormularContent, mSecondFormularContent);
                        } else {
                            onProgressVisible(false);
                        }
                    }
                });

        bindSubscription(kdataListRegister);

        Disposable indictorsRegister = RxBus.getInstance().register(GTSConst.REPLY_MSG_GETINDICATOR + "", Bundle.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bundle>() {

                    @Override
                    public void accept(@NonNull Bundle bundle) throws Exception {
                        if (null != bundle) {
                            GTTIndexDataRequest mGttIndexDataRequest = (GTTIndexDataRequest) bundle.getSerializable("mGttIndexDataRequest");
                            GTTKDataManager.instance().clearIndictor();
                            ReqDataUtils.instance().copyIndictorData(mGttIndexDataRequest);
                            changedIndictors((GTTFormularContent) bundle.getSerializable("SuperFormularContent"),
                                    (GTTFormularContent) bundle.getSerializable("SecondFormularContent"));

                        }
                    }
                });

        bindSubscription(indictorsRegister);

        Disposable kTickRegister = RxBus.getInstance().register(GTSConst.REPLY_KLINETICK_UPDATE + "", Bundle.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bundle>() {

                    @Override
                    public void accept(@NonNull Bundle bundle) throws Exception {
                        if (null != bundle && bundle.getInt("iNotification") == mUiCode) {
                            GTTKDataModel kDataModel2 = (GTTKDataModel) bundle.getSerializable("object");
                            //int addLineNumber = bundle.getInt("addLineNumber");
                            int addLineNumber = ReqDataUtils.instance().updataOrAddLastLine(kDataModel2, (GTTIndexDataRequest) bundle.getSerializable("mRequest"));
                            if (isResumed() && isVisible()) {
                                onRefreshPrice(mUiCode, addLineNumber);
                            }
                        }
                    }
                });

        bindSubscription(kTickRegister);
    }

    /**
     * 请求数据
     */
    public void reqData() {
        isLording();
        Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName());
        if (!isHidden() && NetworkMonitor.hasNetWork() && !ServerConnnectUtil.instance().hasReConnectQuote()) {
            if (isLoading) {
                return;
            }

            if (null == mPeriodicity) {
                mPeriodicity = ChartConfig.instance().getChartPeriodicity();
            }
            ReqDataUtils.instance().isReqLastest = false;
            if (null != mPeriodicity && !ReqDataUtils.instance().isReqLastest) {
                isLoading = true;
                onProgressVisible(true);
                ReqDataUtils.instance().reqKLineData(mUiCode, zoneType, mPeriodicity.nativeKLineType(), 0);
            }
        }
    }

    /**
     * 刷新数据
     */
    public void onRefreshData(int code, int nKLineNum, GTTFormularContent main, GTTFormularContent second) {

        if (null != mKChartView && code == mUiCode) {

            /* new chart **/
            //过滤空数据的情况
            if (GTTKDataManager.instance().mCacheList.size() > 0) {
                isHaveData = true;
                mKChartView.setVisibility(View.INVISIBLE);
                if (ChartConfig.instance().isSecondChartOn()) {
                    mViceChartView.setVisibility(View.INVISIBLE);
                }
                main_rl.setIntercept(false);
                ChartKViewInterfaceimp.setDataList(GTTKDataManager.instance().mCacheList);
                ChartKViewInterfaceimp.setMainIndicator(GTTKDataManager.instance().mSuperIndicators);
                ChartKViewInterfaceimp.setViceIndicator(GTTKDataManager.instance().mSecondIndicators);
                ChartKViewInterfaceimp.refreshData(mUiCode, zoneType, mPeriodicity.nativeKLineType());
                start = System.currentTimeMillis();


            }
            delayLording(main, second);
        }
    }

    private void delayLording(final GTTFormularContent main, final GTTFormularContent second) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    Logger.e("delayLording图表线程id = " + android.os.Process.myTid());
                    Thread.sleep(200);
                    //Logger.i("ChartLibraryLogInfo",METHOD+Thread.currentThread().getStackTrace()[2].getMethodName()+",code="+code+",nKLineNum="+nKLineNum);
                    isLoading = false;
                    isLoaded();
                    if (null == getActivity()) return;
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (GTTKDataManager.instance().reqKLineNumber == 1) {
                                mArrowView.setVisibility(View.VISIBLE);
                            }
                            mKChartView.getAxisRight().resetAxisMinValue();
                            mViceChartView.getAxisRight().resetAxisMinValue();
                            onProgressVisible(false);
                            mKChartView.setVisibility(View.VISIBLE);
                            if (ChartConfig.instance().isSecondChartOn()) {
                                mViceChartView.setVisibility(View.VISIBLE);
                            }
                            setIndictors(main, second);
                            updateIndicatorTitle(GTTKDataManager.instance().mCacheList.size() + 1);
                            resetParams();
                            LayoutParams mBtnParam = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                            mBtnParam.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                            mBtnParam.rightMargin = (int) mKChartView.getViewPortHandler().offsetRight();
                            end_tv.setLayoutParams(mBtnParam);
                        }
                    });
                } catch (Exception e) {
                }
            }
        };
        ThreadPool.getInstance().execute(runnable);
    }

    /**
     * 刷新报价
     */
    public void onRefreshPrice(int code, int addLineNumber) {
        Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName() + ",addLineNumber=" + addLineNumber);
        Logger.i("ChartLibraryLogInfo onRefreshPrice", (!isLoading) + "," + (null != mKChartView) + "," + (GTTKDataManager.instance().kLineNumbers > 0) + "," + (isHaveData)
                + "mUiCode = " + mUiCode + ", code = " + code);
        if (!isLoading && null != mKChartView && mUiCode == code && GTTKDataManager.instance().kLineNumbers > 0 && isHaveData) {
            //刷新最新根线 or 添加新的一根线
            //int addLineNumber = ReqDataUtils.instance().updataOrAddLastLine(mUiCode,mPeriodicity.nativeKLineType(),kDataModel2);
            /** new chart */
            KLineBean kLineBean = new KLineBean();
            kLineBean.date = GTTKDataManager.instance().getLastKLineModel().priceTime + "";
            kLineBean.close = (float) GTTKDataManager.instance().getLastKLineModel().lastPrice;
            kLineBean.open = (float) GTTKDataManager.instance().getLastKLineModel().openPrice;
            kLineBean.high = (float) GTTKDataManager.instance().getLastKLineModel().highPrice;
            kLineBean.low = (float) GTTKDataManager.instance().getLastKLineModel().lowPrice;
            kLineBean.range = GTTKDataManager.instance().getLastKLineModel().range;
            kLineBean.changePrice = GTTKDataManager.instance().getLastKLineModel().changePrice;
            if (addLineNumber > 0) {
                /*
                 * 增加数据
                 */
                ChartKViewInterfaceimp.setMainIndicator(GTTKDataManager.instance().mSuperIndicators);
                ChartKViewInterfaceimp.setViceIndicator(GTTKDataManager.instance().mSecondIndicators);
                ChartKViewInterfaceimp.addNewData(kLineBean);
                updateIndicatorTitle(GTTKDataManager.instance().mCacheList.size() + 1);
            } else if (addLineNumber == 0) {
                /*
                 * 刷新数据
                 */
                ChartKViewInterfaceimp.setMainIndicator(GTTKDataManager.instance().mSuperIndicators);
                ChartKViewInterfaceimp.setViceIndicator(GTTKDataManager.instance().mSecondIndicators);
                ChartKViewInterfaceimp.refreshNewData(kLineBean);
                updateIndicatorTitle(GTTKDataManager.instance().mCacheList.size() + 1);
            }
        }
        end = System.currentTimeMillis();
        Logger.e("spenceTimeInterval", "timeInterval" + Math.abs(end - start));
        if (Math.abs(end - start) > timeInterval) {
            if (null == getActivity()) return;
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mKChartView.notifyDataSetChanged();
                    mKChartView.invalidate();
                    mViceChartView.notifyDataSetChanged();
                    mViceChartView.invalidate();
                }
            });
        } else {
            ThreadPool.getInstance().execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(Math.abs(end - start));
                        if (null == getActivity()) return;
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mKChartView.notifyDataSetChanged();
                                mKChartView.invalidate();
                                mViceChartView.notifyDataSetChanged();
                                mViceChartView.invalidate();
                            }
                        });
                    } catch (Exception e) {
                    }
                }
            });
        }
    }

    /**
     * 失败处理
     */
    public void onFailDeal(int failCode) {
        Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName() + ",failCode=" + failCode);
        isLoading = false;
        onProgressVisible(false);
        String error = ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1012);
        if (ConfigType.SERVER_ERROR_1058.equals(failCode + "")) {
            ReqDataUtils.instance().isReqLastest = true;
            isHaveData = true;
        } else {
            showToastPopWindow(error);
            isHaveData = false;
        }
        isLoaded();
    }

    /**
     * 显示隐藏加载圈
     */
    public void onProgressVisible(boolean isVisible) {
        if (onStatusChangeListener != null) {
            onStatusChangeListener.onProgressVisible(isVisible);
        }
        /*Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName() + ",isVisible=" + isVisible);

        if (getActivity() != null && getActivity() instanceof ChartActivity) {
            ChartActivity activity = (ChartActivity) getActivity();
            activity.onProgressVisible(isVisible);
        } else {
            Logger.e("chartk fragment getActivity is null");
        }*/
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    /**
     * 设置周期
     */
    public void setPeriodicity(Periodicity mPeriod) {
        Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName() + ",mPeriod=" + mPeriod);
        mPeriodicity = mPeriod;
        reqData();
    }

    /**
     * 更新指标值
     *
     * @param curOffset 光标所在线条的位置
     */
    public void updateIndicatorTitle(int curOffset) {
        Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName() + ",curOffset=" + curOffset);
        mCurrOffset = curOffset;
        updateIndicatorTitle(curOffset, true);
        updateIndicatorTitle(curOffset, false);
    }

    /**
     * 更新指标值
     *
     * @param curOffset 光标所在线条的位置
     */
    private void updateIndicatorTitle(int curOffset, final boolean isMain) {
        Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName() + ",curOffset=" + curOffset + ",isMain=" + isMain);
        m_spannableTitle.reset();
        if (GTTKDataManager.instance().hasKLineData()) {

            GTTFormularContent formularContent;
            GTTIndicatorsModel indicatorsModel;
            if (isMain) {
                formularContent = GTTKDataManager.instance().mSuperFormularContent;
                indicatorsModel = GTTKDataManager.instance().mSuperIndicators;
            } else {
                formularContent = GTTKDataManager.instance().mSecondFormularContent;
                indicatorsModel = GTTKDataManager.instance().mSecondIndicators;
            }

            //指标参数默认值
            if (null != formularContent && formularContent.mParamNum > 0) {
                String formularInfo = "(";
                for (int i = 0; i < formularContent.mParamNum; i++) {
                    GTTFormularParam param = formularContent.mParamList.get(i);
                    if (i != formularContent.mParamNum - 1) {
                        formularInfo += DoubleConverter.toZeroOr2Decimal(param.mDefaultVal) + ",";
                    } else {
                        formularInfo += DoubleConverter.toZeroOr2Decimal(param.mDefaultVal);
                    }
                }
                formularInfo += ")  ";
                boolean isNight = false;
                if (onStatusChangeListener != null) {
                    isNight = onStatusChangeListener.isNight();
                }
                if (isNight) {
                    m_spannableTitle.setForegroundColorSpanString(formularInfo, 0xFF99A6B3);
                } else {
                    m_spannableTitle.setForegroundColorSpanString(formularInfo, ColorThemeUtil.instance().color_b);
                }
            }

            //指标参数名及指标值
            if (indicatorsModel != null && indicatorsModel.mLineList.size() > 0) {
                int lineIdx = 0;
                ArrayList<GTTLineModel> mLines = indicatorsModel.mLineList;
                for (GTTLineModel line : mLines) {
                    String lineInfo = "";
                    if (lineIdx < mLines.size()) {
                        if ("L0".equals(mLines.get(lineIdx)) && mLines.size() == 1) {
                            lineInfo += indicatorsModel.mName.toUpperCase() + ":";
                        } else {
                            lineInfo += mLines.get(lineIdx).mName.toUpperCase() + ":";
                        }
                        List<Double> mTmpValue = line.mLineData.mLines;// 提取指标值，默认取最后一根线对应的值,光标移动则取光标对应的指标值
                        if (null != mTmpValue && mTmpValue.size() > 0) {
                            int total = GTTKDataManager.instance().mCacheList.size();
                            int number = total - mTmpValue.size();
                            //curOffset=curOffset-number;
                            int chooseIndex = curOffset - number;
                            if (chooseIndex > mTmpValue.size() - 1) {
                                chooseIndex = mTmpValue.size() - 1;
                            }
                            Double mValue;
                            if (chooseIndex < 0) {
                                //curOffset = GTTKDataManager.instance().firstLineIndex + GTTKDataManager.instance().barsPerGrid();
                                mValue = 0.0d;
                            } else {
                                mValue = mTmpValue.get(chooseIndex);
                            }
                            //                            Logger.e("curOffset = " + curOffset);
                            // 如果指标值超过此范围值，表示存在数据为空的情况，此时指标值取0
                            if (mValue >= 100000000 || mValue <= -100000000) {
                                mValue = 0.0d;
                            }
                            lineInfo += mPrecision.format(mValue);
                        }
                        lineInfo += "  ";
                    }
                    m_spannableTitle.setForegroundColorSpanString(lineInfo, line.mColor);
                    lineIdx++;
                }
            }
        }
        if (getActivity() != null) {
            getActivity().runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    if (isMain) {
                        mMainTitleView.setText(m_spannableTitle.getBuilder());
                    } else {
                        mSecondTitleView.setText(m_spannableTitle.getBuilder());
                    }
                }
            });
        }
    }

    /**
     * 主图指标设置
     */
    @OnClick(R.id.main_set_btn)
    void showMainSetting() {
        Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName());
        ActivityManager.showChartSetActivity(getActivity(), ChartConfig.instance().getMainKType());
    }

    /**
     * 副图指标设置
     */
    @OnClick(R.id.second_set_btn)
    void showSecondSetting() {
        Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName());
        ActivityManager.showChartSetActivity(getActivity(), ChartConfig.instance().getSecondKType());
    }

    /**
     * 主图指标按钮点击
     */
    @OnClick(R.id.main_btn_layout)
    void showMainIndicator() {
        Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName());
        showIndicatorPop();
    }

    /**
     * 副图指标按钮点击
     */
    @OnClick(R.id.second_btn_layout)
    void showSecondIndicator() {
        Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName());
        showIndicatorPop();
    }

    /**
     * 滑动到最右端按钮点击
     */
    @OnClick(R.id.arrow_view)
    void toRightKline() {
        Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName());
        if (null != mKChartView && null != mViceChartView) {
            cleanHighLight();
            mKChartView.moveLastIndex();
            mKChartView.invalidate();
            mViceChartView.moveLastIndex();
            mViceChartView.invalidate();
        }
    }

    /**
     * 显示指标菜单弹层
     */
    private void showIndicatorPop() {
        Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName());
        if (mIndicatorPop == null) {
            mIndicatorPop = new ChartIndicatorPopWindow(getActivity(), new RecyclerClickListener() {
                @Override
                public void onClick(int position, DataItemDetail itemDetail) {
                    mCurSecondIndictor = position;
                }
            });
        }

        mIndicatorPop.setOnDismissedListener(new DialogDismissedListener() {


            @Override
            public void onDismissed(BaseDialog dialog) {
                AppTerminal.instance().asyncCalcIndicator(mUiCode);
            }
        });
        if (!mIndicatorPop.isShowing()) {
            mIndicatorPop.show();
        } else {
            mIndicatorPop.dismiss();
        }
    }

    /**
     * 重置现价线
     */
    public void resetNowPrice(boolean select) {
        Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName() + ",select=" + select);
        mKChartView.showNowPrice(select);
        mKChartView.invalidate();
    }

    /**
     * 设置阳线类型
     */
    public void setStype() {
        Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName());
        ChartKViewInterfaceimp.setPaintStype();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName() + ",hidden=" + hidden);
        super.onHiddenChanged(hidden);
        cleanHighLight();
        if (!hidden) {
            setPeriodicity(ChartConfig.instance().getChartPeriodicity());
        }
    }

    public void setProductDecimalNum(int num) {
        Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName() + ",num=" + num);
        if (num != decimalNum && null != ChartKViewInterfaceimp) {
            mPrecision = new ProductPrecision(0, num);
            ChartKViewInterfaceimp.setProductPrecision(mPrecision);
            decimalNum = num;
            ChartKViewInterfaceimp.refreshDecimalNum(num);
            cleanHighLight();
            updateIndicatorTitle(GTTKDataManager.instance().mCacheList.size() + 1);
        }
    }

    /**
     * 清除光标
     **/
    private void cleanHighLight() {
        Logger.i("ChartLibraryLogInfo", METHOD + Thread.currentThread().getStackTrace()[2].getMethodName());
        mKChartView.highlightValue(null);
        mViceChartView.highlightValue(null);
    }

    /**
     * 无数据
     **/
    public void noDate(int failCode) {
        mMainTitleView.setText("");
        mSecondTitleView.setText("");
        /*mKChartView.setVisibility(View.INVISIBLE);
        mViceChartView.setVisibility(View.INVISIBLE);*/
        mArrowView.setVisibility(View.INVISIBLE);
        onFailDeal(failCode);
        noDataView();
    }

    /**
     * 正在加载数据
     **/
    public void isLording() {
        mKChartView.setTouchEnabled(false);
        mViceChartView.setTouchEnabled(false);
    }

    /**
     * 加载数据完毕
     **/
    public void isLoaded() {
        mKChartView.setTouchEnabled(true);
        mViceChartView.setTouchEnabled(true);
    }

    /**
     * 无数据情况图表显示
     **/
    public void noDataView() {
        main_rl.setIntercept(true);
        mKChartView.noDataView();
        mViceChartView.noDataView();
        isLoading = false;
        isLoaded();
    }

    public void onNightMode(boolean isNight) {
        if (isNight) {
            main_rl.setBackgroundColor(getResources().getColor(R.color.color_night_bg_d2));
            mMainSet.setColorFilter(getResources().getColor(R.color.color_f));
            mSecondSet.setColorFilter(getResources().getColor(R.color.color_f));
            mMainTarget.setBackgroundResource(R.drawable.chart_indic_btn_bg_night);
            mSecondTarget.setBackgroundResource(R.drawable.chart_indic_btn_bg_night);
            start_tv.setTextColor(0xFF99A6B3);
            end_tv.setTextColor(0xFF99A6B3);
            //ChartKViewInterfaceimp.setYAxisTextColor(0xFF99A6B3);
        } else {
            main_rl.setBackgroundColor(getResources().getColor(R.color.color_f));
            mMainSet.clearColorFilter();
            mSecondSet.clearColorFilter();
            mMainTarget.setBackgroundResource(R.drawable.chart_indic_btn_bg);
            mSecondTarget.setBackgroundResource(R.drawable.chart_indic_btn_bg);
            start_tv.setTextColor(getResources().getColor(R.color.color_888888));
            end_tv.setTextColor(getResources().getColor(R.color.color_888888));
            //ChartKViewInterfaceimp.setYAxisTextColor(getResources().getColor(R.color.color_text));
        }
        if (mCurrOffset > 0) {
            updateIndicatorTitle(mCurrOffset);
        }
        onChartNight(mKChartView, isNight);
        onChartNight(mViceChartView, isNight);
    }

    private void onChartNight(MyCombinedChart chart, boolean isNight) {
        YAxis leftAxis = chart.getAxisLeft();
        YAxis rightAxis = chart.getAxisRight();
        XAxis xAxis = chart.getXAxis();
        if (isNight) {
            if (rightAxis != null) {
                rightAxis.setGridColor(getResources().getColor(R.color.color_night_line));
                rightAxis.setTextColor(getResources().getColor(R.color.color_night_text));
            }
            if (leftAxis != null) {
                leftAxis.setGridColor(getResources().getColor(R.color.color_night_line));
            }
            if (xAxis != null) {
                xAxis.setGridColor(getResources().getColor(R.color.color_night_line));
            }
            chart.setBorderColor(getResources().getColor(R.color.color_night_line));
        } else {
            if (rightAxis != null) {
                rightAxis.setGridColor(getResources().getColor(R.color.color_line));
                rightAxis.setTextColor(getResources().getColor(R.color.color_888888));
            }
            if (leftAxis != null) {
                leftAxis.setGridColor(getResources().getColor(R.color.color_line));
            }
            if (xAxis != null) {
                xAxis.setGridColor(getResources().getColor(R.color.color_line));
            }
            chart.setBorderColor(ChartThemeUtil.instance().color_line);
        }
        chart.postInvalidate();
    }

    public void setOnStatusChangeListener(OnQuoteChartProgressStatusChangeListener onStatusChangeListener) {
        this.onStatusChangeListener = onStatusChangeListener;
    }

    public void setUiCodeAndZoneType(int uiCode, int zoneType) {
        this.mUiCode = uiCode;
        this.zoneType = zoneType;
        GTTKDataManager.instance().clearIndictor();
        GTTKDataManager.instance().clearKData();
        initViewData();
    }

    public void setOnPriceBarListener(OnPriceBarListener listener) {
        this.priceBarListener = listener;
    }

    public interface OnPriceBarListener {

        void onShowCursor(boolean enabled);

        void onHideCursor(int uiCode);

        void onDrawCursor(double closePrice, GTTKDataModel dataModel, ProductPrecision precision);

    }

}
